#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>


#define SERVER_TCP_PORT 12347
#define SIZE 512

int sigflag;

int err_stop (char* msg)
{
	printf("%s \n",msg);
	exit(-1);
}


int main(int argc, char*argv[ ]) 
{
	int numberProcess=0;
	int sd2,childpid;

 	int sockfd, clilen,n;

 	struct sockaddr_in serv_addr, cli_addr;  /*we assume this responder is a server and the intiator is a client*/
 	/* message size*/
 	//char msg[SIZE];
	//calculer le nombre de processus

	char * command="ps ax | wc -l | sed -e \"s: ::g\"";
	printf("%s\n",command);

  	// Open a TCP socket (an Internet streams socket)
	if ( (sockfd = socket (PF_INET, SOCK_STREAM, 0)) < 0){
     	 	err_stop ("server: can't open datagram socket");  //we assume this performs perror() and exit(-1)
		exit(-1);
	}
	
	//Bind our local address so that the client can send to  us

       bzero((char *) &serv_addr, sizeof(serv_addr));
       serv_addr.sin_family      = AF_INET;
       serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
       serv_addr.sin_port        = htons(SERVER_TCP_PORT);


       if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
		err_stop ("server: can't bind local address");
		exit(-1);	
       }

      /*set up queue for connection request */

	
	//print server port and IP address
	//inet_ntoa convert the server address into a string 
	printf("SERVER ADDRESS : %s \n", (char*)inet_ntoa(serv_addr.sin_addr));
	printf("SERVER PORT : %d \n", SERVER_TCP_PORT);
	
	// Set de maximum number of pending requests
	 if(listen(sockfd,5)<0){
         	err_stop("listen error : Server queue full ");
         	exit(-1);
	 }
	
	//char * command="ps ax | wc -l | sed -e \"s: ::g\"";
	for(;;){
		sigflag = 0;


          	/* Wait for a connection from a client processes.
           	 */
		clilen = sizeof(cli_addr); 
		if ((sd2 = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) > 0){
			
			char *clienthost;
			int cli_port;
			
			clienthost = (char*)inet_ntoa(cli_addr.sin_addr);
        	cli_port = ntohs(cli_addr.sin_port);
        	printf("[Info]: Connexion au service de port [%d] :Client en provenance de l'hoste [%s] dont le port est [%d] en cours de service\n",SERVER_TCP_PORT,clienthost, cli_port);
			
				/*Accept request from all network interfaces of any machine 
                         *(each network interface has a separate IP address) */
				{ 
            			if(sigflag == 1)continue; 

                   		/*just in case we get SIGCHLD during accept*/                                      
             			//perror("accept error in server");
             			//exit(-1);
          		}
			
				if((childpid = fork()) < 0){
					perror("fork error in telnetd");
             		exit(-1);					
				}
				else if(childpid == 0){
					close(sockfd);    
					char msg[SIZE];
					if((n = recv (sd2, msg,SIZE,0)) > 0){
					
					
						FILE *f= popen(command, "r");
						if (f == NULL) {
		  					fprintf(stderr, "Can't execute the command!\n");
		  					exit(1);//
						}						
						while (fscanf(f, "%d", &numberProcess) != EOF) {
						}
		 				//printf("%d \n", numberProcess);					
						char response[SIZE];
						sprintf(response,"le nombre des processus est :%d\n",numberProcess);
						if(send (sd2,response,strlen(response),0) < 0){
							err_stop ("server: send error");
							close(sd2);
						}
					}
				printf("[Info] : Service port [%d] : Fin de service du client en provenances de l'hoste [%s] dont le port est [%d]\n",SERVER_TCP_PORT,clienthost, cli_port);			
				close(sd2);   
				exit(0);     	
			}
		}
	}	
	exit(0);
	
}




